//0、新箱称重；1、空箱入库；2、空箱出库
let type = 2;
$(document).ready(function () {
    /*if (Cookies.get("optionType")) {
        type = Cookies.get("optionType");
    }*/

    $('.confirm-btn').on('click', function () {
        const value = $('.input').val();
        initByInput(value);
        emptyBtnClick();
    });

    //初始化select默认选中温区
    $("#temp-num").val($("#temperature-id").val());

    //render方法强制重新渲染引导程序 - 选择ui,如果当您编程时更改任何相关值而影响元素布局，这将非常有用。
    $('#select-id').selectpicker('render');

    $("#select-id").on("changed.bs.select", function (e) {
        type = $(this).val();
        //防止回调过程中，浏览器关闭（理论上只有一条数据会出问题，测试&&试运营观察）type取默认值
        // Cookies.set("optionType", type);
        if (type == 2 || type == 1) {
            $('#outbound-number').removeAttr("disabled");
            $('#temperature-id').removeAttr("disabled");
        } else {
            $('#outbound-number').attr("disabled", "disabled");
            // $('#temperature-id').attr("disabled", "disabled");
            $('#outbound-number').val(1);
            // $('#temperature-id').selectpicker('val', ['noneSelectedText']);
            // $('#temperature-id').selectpicker('refresh');
        }
        $('#temperature-id').selectpicker('val', ['101']);
        $('#temperature-id').selectpicker('refresh');
    });

    //render方法强制重新渲染引导程序 - 选择ui,如果当您编程时更改任何相关值而影响元素布局，这将非常有用。
    $('#temperature-id').selectpicker('render');
    $("#temperature-id").on("changed.bs.select", function (e) {
        let temp = $(this).val();
        $('#temp-num').val(temp);
        $('#emptyNumber').focus();
    });
    //render方法强制重新渲染引导程序 - 选择ui,如果当您编程时更改任何相关值而影响元素布局，这将非常有用。
    $('#goods-box-spec-id').selectpicker('render');
    $("#goods-box-spec-id").on("changed.bs.select", function (e) {
        let temp = $(this).val();
        $('#goods-box-spec-type').val(temp);
        $('#emptyNumber').focus();
    });

    $('#emptyNumber').focus();

});
//监听服务器连接事件
/*socket.on("connect", function () {
    selectResponseFromWcs("weighResp", $("#client-id").val(), 5, true, weighRespCallBack);
    selectResponseFromWcs("connect_error", $("#client-id").val(), 5, false, connectErrorCallBack);
    selectResponseFromWcs("wcsToWmsResponse", $("#client-id").val(), 5, false, wcsToWmsResponseCallBack);
    selectResponseFromWcs("storageDone", $("#client-id").val(), 3, true, storageDoneCallBack);
});*/

function storageDoneCallBack(data, cancel, opt) {
    if (!cancel) {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }
    }
}

//回调处理
function weighRespCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log(">>>>>>>>>>称重回调");
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        $("#empty-btn").hide();
    } else {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
            if (type == 0) {
                console.log("称重成功");
                console.log("称重信息：" + JSON.stringify(obj));
                $('#ware-box-code').val("");
                $('#empty-btn').show();
                $('.message').text(obj.boxCode + "称重成功");
            } else if (type == 1) {
                upBox();
            } else if (type = 2) {
                $('#ware-box-code').val("");
            }
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }

    }
}

//发送指令响应回调
function wcsToWmsResponseCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        // dealWithError("emptyNumber",'');
    } else {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        clearInput("emptyNumber");
        console.log("KKKKKK:" + JSON.stringify(obj));
        if (obj.code == 1) {
            // dealWithError("emptyNumber", obj.msg);
            $('#message-content').text(obj.msg);
            $("#empty-btn").show();
        } else {
            $('#message-content').text("操作成功！");
            $("#ware-box-code").val("");
            $('#total-weight-download').val("");
            if (obj.processState == 21 && obj.processType == 5) {
                //货箱净重称重响应成功，则入库
                initByInput(obj.boxCode);
                upBox();
            }
            $("#empty-btn").show();
        }
        setTimeout("$('#message-content').text('')", 7000);
    }
}

//分拣称重
function sortWeightCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("分拣称重响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }
    }
}

//货箱离开库位
function leaveBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("入库离开缓存位响应：" + JSON.stringify(data));
    $("#empty-btn").show();
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
        } else {
            BootstrapDialog.alert(obj.msg);
        }
    }
}

//出库到缓存位
function inBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("obj:" + JSON.stringify(data.data));
    if (!cancel) {
        //todo 逻辑处理
        const obj = data.data;
        if (obj.code == 0) {
            outDown(obj);
        } else {
            delResponseFromWcs(data, opt);
        }

    } else {
        //todo 按钮隐藏之类的
    }
}

//入库缓存位扫码响应
function pageEntryCallBack(data) {
    console.log("入库缓存位扫码响应：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.code==0) {
            if(type ==0 || type == 1){
                const resultData = vc.data;
                $("#emptyNumber").val(resultData.BoxCode);
                $("#empty-btn").click();
            }else{
                BootstrapDialog.alert("当前选择为非货箱称重或者货箱入库，货箱放到缓存位无效");
            }
        }else{
            BootstrapDialog.alert(vc.msg);
        }
    }
}

//要是新货箱，第一次是净重称重，然后在响应流程中，重新调用入库
function emptyBtnClick() {
    const boxCode = $('#ware-box-code').val();
    $("#empty-btn").hide();
    //第一次扫货箱编号，默认为称重，称重响应成功后，再校验是否入库，称过重的则再称
    console.log(">>>>>>" + type);
    if (type == 0) {
        netWeight();
    } else if (type == 1) {
        upBox();
    } else if (type == 2) {
        // downByNumber();
        if (!$('#temperature-id').attr('disabled') && !$('#outbound-number').attr('disabled')) {
            //货箱为空，且删除disabled，出库
            downByNumber();
        } else {
            clearInput("emptyNumber");
        }
    }

}

//根据数量出库
function downByNumber() {
    const number = $('#outbound-number').val();
    if (!number) {
        $('#message-content').text("请输入数字");
        setTimeout("$('#message-content').text('')", 5000);
        $('#outbound-number').focus();
        $('#empty-btn').show();
        return;
    }
    if (!isUnsignedInteger(number)) {
        $('#message-content').text("请输入1-99的数字");
        setTimeout("$('#message-content').text('')", 5000);
        $('#outbound-number').focus();
        $('#empty-btn').show();
        return;
    }
    if (parseInt(number) == 0) {
        $('#message-content').text("请输入大于0的数字");
        setTimeout("$('#message-content').text('')", 5000);
        $('#outbound-number').focus();
        $('#empty-btn').show();
        return;
    }

    if ($('#temperature-id').attr('disabled') && $('#outbound-number').attr('disabled')) {
        //存在disabled
    } else {
        $('#outboundNumber').val(number);
        $('#total-weight-download').val(number);
        //删除disabled，说明出库，且指定数量空箱出库
        const boxCode = $('#ware-box-code').val();
        if (boxCode) {
            //指定货箱下架，且出库数量大于1，给个提示
            if (number > 1) {
                BootstrapDialog.confirm({
                    title: '信息提示',
                    message: '出库时，当输入货箱编号后，将以货箱编号出库，而不按照出库数量出库，是否确定出库?',
                    btnCancelLabel: '取消', // <-- Default value is 'Cancel',
                    btnOKLabel: '确定', // <-- Default value is 'OK',
                    callback: function (result) {
                        if (result) {
                            notEntryByBoxCode();
                        }else{
                            $('#empty-btn').show();
                        }
                    }
                });
            } else {
                notEntryByBoxCode();
            }
        } else {
            notEntryEmptyBox();
        }
    }


}

//不指定货箱编号下架，即可批量下
function notEntryEmptyBox() {
    const tempNum = $('#temp-num').val();
    if (!tempNum) {
        //默认常温区
        $('#temp-num').val($("#temperature-id").val());
    }
    const opt = $("#form-param").serializeJSON();
    // $('#total-weight-num').val($('#outbound-number').val());
    $('#total-weight-download').val($('#outbound-number').val());
    $('#ware-box-code').val("");
    $.ajax({
        type: "POST",
        url: "/wcs/notEntryEmptyBox",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                //入库成功
                $('#empty-btn').show();
            } else {
                dealWithError("emptyNumber", data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

//指定货箱编号出库（不论是空箱还是非空箱），走非空箱出库流程
function notEntryByBoxCode() {
    // $('#temp-num').val("");
    $('#goods-box-spec-type').val("");
    // $('#total-weight-num').val("");
    $('#total-weight-download').val(1);
    const opt = $("#form-param").serializeJSON();
    console.log(JSON.stringify(opt));
    opt['operationPage'] = 1;
    $.ajax({
        type: "POST",
        url: "/wcs/notEntryByBoxCode",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                //入库成功
                $('#goods-box-spec-type').val("0");
            } else {
                dealWithError("emptyNumber", data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

function upBox() {
    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/emptyEntry",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            if (data.code == 0) {
            } else {
                dealWithError("emptyNumber", data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

function dealWithError(buttonId, msg) {
    $('#message-content').text(msg);
    $('#empty-btn').show();
    $('#ware-box-code').val("");
    clearInput(buttonId);
    setTimeout("$('#message-content').text('')", 7000);
}

//净重称重
function netWeight() {
    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/netWeight",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                clearInput("emptyNumber");
            } else {
                BootstrapDialog.show({
                    size: BootstrapDialog.SIZE_NORMAL,
                    message: data.msg,
                    closable: false,
                    buttons: [{
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }]
                });
                $("#emptyNumber").focus();
                $('#empty-btn').show();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

//净重称重
function netWeight() {
    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/netWeight",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                clearInput("emptyNumber");
            } else {
                BootstrapDialog.show({
                    size: BootstrapDialog.SIZE_NORMAL,
                    message: data.msg,
                    closable: false,
                    buttons: [{
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }]
                });
                $("#emptyNumber").focus();
                $('#empty-btn').show();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

//箱子出库到位
function outDown(data) {
    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/box/downloadEmptyBox",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(data),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                BootstrapDialog.show({
                    size: BootstrapDialog.SIZE_NORMAL,
                    message: data.msg,
                    closable: false,
                    buttons: [{
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }]
                });
                $("#emptyNumber").focus();
                $('#empty-btn').show();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}